package com.leyou.gateway.filter;

import com.leyou.auth.constans.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.utils.JwtUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 刷新页面
 */
@Component
public class AuthFilter implements GlobalFilter {
    @Autowired
    private  JwtUtils jwtUtils;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取jwt
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie cookie = cookies.getFirst(JwtConstants.COOKIE_NAME);
        if(cookie == null){
            //放行
            return chain.filter(exchange);
        }
        //2.验证是否登录
        try {
            Payload payload = jwtUtils.parseJwt(cookie.getValue());
            //已登录
            //3.刷新
            jwtUtils.refresh(payload.getUserDetail().getId());
        } catch (Exception e) {
            //未登录,无需刷新
            e.printStackTrace();
        }
        //放行
        return chain.filter(exchange);
    }
}
